/* 
Author: Christian Bailer
Contact address: Christian.Bailer@dfki.de 
Department Augmented Vision DFKI 

                          License Agreement
               For Open Source Computer Vision Library
                       (3-clause BSD License)

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

  * Neither the names of the copyright holders nor the names of the contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are disclaimed.
In no event shall copyright holders or contributors be liable for any direct,
indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused
and on any theory of liability, whether in contract, strict liability,
or tort (including negligence or otherwise) arising in any way out of
the use of this software, even if advised of the possibility of such damage.
*/

#pragma once

#ifndef FFTTOOLS_HPP_
#define FFTTOOLS_HPP_

// opencv
// #include <opencv2/core/core.hpp>
#include "cv_mat.hpp"
//#include "dsp_intrinsics.h"
//NOTE: FFTW support is still shaky, disabled for now.
/*#ifdef USE_FFTW
#include <fftw3.h>
#endif*/

namespace FFTTools
{

// Previous declarations, to avoid warnings
// cv::Mat fftd(cv::Mat img, bool backwards = false);
// cv::Mat real(cv::Mat img);
// cv::Mat imag(cv::Mat img);
// cv::Mat magnitude(cv::Mat img);
// cv::Mat complexMultiplication(cv::Mat a, cv::Mat b);
// cv::Mat complexDivision(cv::Mat a, cv::Mat b);
// void rearrange(cv::Mat &img);
// void normalizedLogTransform(cv::Mat &img);

// cv::Mat fftd(cv::Mat img, bool backwards)
// {
//     if (img.channels() == 1)
//     {
//         cv::Mat planes[] = {cv::Mat_<float> (img), cv::Mat_<float>::zeros(img.size())};
//         cv::merge(planes, 2, img);
//     }
//     cv::dft(img, img, backwards ? (cv::DFT_INVERSE | cv::DFT_SCALE) : 0 );

//     return img;
// }
// twiddles: qhdsp_fft_gen_twiddles_real_acf()
CvMatF32Complex fftd(CvMatF32 &img, const float complex* twiddles1, const float complex* twiddles2, const float complex* twiddles)
{
    int32_t np = img.rows;
    CvMatF32Complex dst(np, np);
    CvMatF32Complex tmp(np, np);
//    FARF(RUNTIME_HIGH, "--------1------fftd");
    // 1d fft
    for (int i = 0; i < np; i++) {
        qhdsp_acf_r1dfft_af(img.data+i*np, np, twiddles1, twiddles2, tmp.data+i*np);
    }
//    FARF(RUNTIME_HIGH, "--------2------fftd");
    //transpose
    for (int i = 0; i < np; i++) {
        for (int j = 0; j < np; j++) {
            dst(i, j) = tmp(j, i);
        }
    }
//    FARF(RUNTIME_HIGH, "--------3------fftd");
    // 1d fft
    for (int i = 0; i < np; i++) {
        qhdsp_c1dfft_acf(dst.data+i*np, np, twiddles, tmp.data+i*np);
    }
//    FARF(RUNTIME_HIGH, "--------4------fftd");
    // transpose
    for (int i = 0; i < np; i++) {
        for (int j = 0; j < np; j++) {
            dst(i, j) = tmp(j, i);
        }
    }
//    FARF(RUNTIME_HIGH, "--------5------fftd");
//    printf("--------dst\n");
//	for (int i = 0; i < np; i++) {
//		for (int j = 0; j < np; j++) {
//			printf("%.4f+%.4fi, ", qhcomplex_creal_f(dst(i,j)), qhcomplex_cimag_f(dst(i,j)));
//		}
//		printf("\n");
//	}
    return dst;
}
// twiddles: qhdsp_fft_gen_twiddles_real_acf()
// CvMatF32Complex ifftd(CvMatF32Complex &img, const float complex* twiddles1, const float complex* twiddles2, const float complex* twiddles)
// {
//     CvMatF32Complex dst(np, np);
//     CvMatF32Complex tmp(np, np);
//     // qhdsp_af_r1difft_acf(img.data, img.rows*img.cols, twiddles1, twiddles2, dst.data);
//     // 1d fft
//     for (int i = 0; i < img.rows; i++) {
//         qhdsp_af_r1difft_acf(img.data, np, twiddles1, twiddles2, tmp.data);
//     }
//     //transpose
//     for (int i = 0; i < np; i++) {
//         for (int j = 0; j < np; j++) {
//             dst(i, j) = tmp(j, i);
//         }
//     }
//     // 1d fft
//     for (int i = 0; i < np; i++) {
//         qhdsp_c1difft_acf(dst.data, np, twiddles, tmp.data);
//     }
//     // transpose
//     for (int i = 0; i < np; i++) {
//         for (int j = 0; j < np; j++) {
//             dst(i, j) = tmp(j, i);
//         }
//     }
//     return dst;
// }

// twiddles: qhdsp_fft_gen_twiddles_complex_acf();
CvMatF32Complex cfftd(CvMatF32Complex &img, const float complex* twiddles)
{
    int32_t np = img.rows;
    CvMatF32Complex dst(np, np);
    CvMatF32Complex tmp(np, np);
    // qhdsp_c1dfft_acf(img.data, img.rows*img.cols, twiddles, dst.data);
    // 1d fft
    for (int i = 0; i < np; i++) {
        qhdsp_c1dfft_acf(img.data+i*np, np, twiddles, tmp.data+i*np);
    }
    //transpose
    for (int i = 0; i < np; i++) {
        for (int j = 0; j < np; j++) {
            dst(i, j) = tmp(j, i);
        }
    }
    // 1d fft
    for (int i = 0; i < np; i++) {
        qhdsp_c1dfft_acf(dst.data+i*np, np, twiddles, tmp.data+i*np);
    }
    // transpose
    for (int i = 0; i < np; i++) {
        for (int j = 0; j < np; j++) {
            dst(i, j) = tmp(j, i);
        }
    }
//        printf("--------dst\n");
//    	for (int i = 0; i < np; i++) {
//    		for (int j = 0; j < np; j++) {
//    			printf("%.4f+%.4fi, ", qhcomplex_creal_f(dst(i,j)), qhcomplex_cimag_f(dst(i,j)));
//    		}
//    		printf("\n");
//    	}
    return dst;
}

CvMatF32Complex icfftd(CvMatF32Complex &img, const float complex* twiddles)
{
    int32_t np = img.rows;
    CvMatF32Complex dst(np, np);
    CvMatF32Complex tmp(np, np);
    // qhdsp_c1difft_acf(img.data, img.rows*img.cols, twiddles, dst.data);
    // 1d fft
    for (int i = 0; i < np; i++) {
        qhdsp_c1difft_acf(img.data+i*np, np, twiddles, tmp.data+i*np);
    }
    //transpose
    for (int i = 0; i < np; i++) {
        for (int j = 0; j < np; j++) {
            dst(i, j) = tmp(j, i);
        }
    }
    // 1d fft
    for (int i = 0; i < np; i++) {
        qhdsp_c1difft_acf(dst.data+i*np, np, twiddles, tmp.data+i*np);
    }
    // transpose
    for (int i = 0; i < np; i++) {
        for (int j = 0; j < np; j++) {
            dst(i, j) = tmp(j, i);
        }
    }
    return dst;
}

// cv::Mat real(cv::Mat img)
// {
//     std::vector<cv::Mat> planes;
//     cv::split(img, planes);
//     return planes[0];
// }
CvMatF32 real(CvMatF32Complex &img)
{
    CvMatF32 tmp;
    tmp.resize(img.rows, img.cols);
    for (int r = 0; r < img.rows; r++) {
        for (int c = 0; c < img.cols; c++) {
            tmp(r, c) = qhcomplex_creal_f(img(r, c));
        }
    }
    return tmp;
}

// cv::Mat imag(cv::Mat img)
// {
//     std::vector<cv::Mat> planes;
//     cv::split(img, planes);
//     return planes[1];
// }
CvMatF32 imag(CvMatF32Complex &a)
{ 
    CvMatF32 tmp;
    tmp.resize(a.rows, a.cols);
    for (int r = 0; r < a.rows; r++) {
        for (int c = 0; c < a.cols; c++) {
            tmp(r, c) = qhcomplex_cimag_f(a(r, c));
        }
    }
    return tmp;
}

// cv::Mat magnitude(cv::Mat img)
// {
//     cv::Mat res;
//     std::vector<cv::Mat> planes;
//     cv::split(img, planes); // planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))
//     if (planes.size() == 1) res = cv::abs(img);
//     else if (planes.size() == 2) cv::magnitude(planes[0], planes[1], res); // planes[0] = magnitude
//     else assert(0);
//     return res;
// }

// cv::Mat complexMultiplication(cv::Mat a, cv::Mat b)
// {
//     std::vector<cv::Mat> pa;
//     std::vector<cv::Mat> pb;
//     cv::split(a, pa);
//     cv::split(b, pb);

//     std::vector<cv::Mat> pres;
//     pres.push_back(pa[0].mul(pb[0]) - pa[1].mul(pb[1]));
//     pres.push_back(pa[0].mul(pb[1]) + pa[1].mul(pb[0]));

//     cv::Mat res;
//     cv::merge(pres, res);

//     return res;
// }
CvMatF32Complex complexMultiplication(CvMatF32Complex &a, CvMatF32Complex &b)
{
    CvMatF32Complex dst(a.rows, a.cols);
    for (int i = 0; i < dst.rows; i++) {
        for (int j = 0; j < dst.cols; j++) {
            float a_real = qhcomplex_creal_f(a(i, j));
            float a_imag = qhcomplex_cimag_f(a(i, j));
            float b_real = qhcomplex_creal_f(b(i, j));
            float b_imag = qhcomplex_cimag_f(b(i, j));

            float real = a_real*b_real - a_imag*b_imag;
            float imag = a_real*b_imag + a_imag*b_real;
            dst(i, j) = {real, imag};
        }
    }
    return dst;
}

// cv::Mat complexDivision(cv::Mat a, cv::Mat b)
// {
//     std::vector<cv::Mat> pa;
//     std::vector<cv::Mat> pb;
//     cv::split(a, pa);
//     cv::split(b, pb);

//     cv::Mat divisor = 1. / (pb[0].mul(pb[0]) + pb[1].mul(pb[1]));

//     std::vector<cv::Mat> pres;

//     pres.push_back((pa[0].mul(pb[0]) + pa[1].mul(pb[1])).mul(divisor));
//     pres.push_back((pa[1].mul(pb[0]) + pa[0].mul(pb[1])).mul(divisor));

//     cv::Mat res;
//     cv::merge(pres, res);
//     return res;
// }

CvMatF32Complex complexDivision(CvMatF32Complex &a, CvMatF32Complex &b)
{
    CvMatF32Complex dst(a.rows, a.cols);
    for (int i = 0; i < dst.rows; i++) {
        for (int j = 0; j < dst.cols; j++) {
            float a_real = qhcomplex_creal_f(a(i, j));
            float a_imag = qhcomplex_cimag_f(a(i, j));
            float b_real = qhcomplex_creal_f(b(i, j));
            float b_imag = qhcomplex_cimag_f(b(i, j));
            float divisor = qhmath_div_f(1.f, b_real*b_real+b_imag*b_imag);
            float real = (a_real*b_real + a_imag*b_imag)*divisor;
            float imag = (a_imag*b_real + a_real*b_imag)*divisor;
            dst(i, j) = {real, imag};
        }
    }
    return dst;
}

// void rearrange(cv::Mat &img)
// {
//     // img = img(cv::Rect(0, 0, img.cols & -2, img.rows & -2));
//     int cx = img.cols / 2;
//     int cy = img.rows / 2;

//     cv::Mat q0(img, cv::Rect(0, 0, cx, cy)); // Top-Left - Create a ROI per quadrant
//     cv::Mat q1(img, cv::Rect(cx, 0, cx, cy)); // Top-Right
//     cv::Mat q2(img, cv::Rect(0, cy, cx, cy)); // Bottom-Left
//     cv::Mat q3(img, cv::Rect(cx, cy, cx, cy)); // Bottom-Right

//     cv::Mat tmp; // swap quadrants (Top-Left with Bottom-Right)
//     q0.copyTo(tmp);
//     q3.copyTo(q0);
//     tmp.copyTo(q3);
//     q1.copyTo(tmp); // swap quadrant (Top-Right with Bottom-Left)
//     q2.copyTo(q1);
//     tmp.copyTo(q2);
// }
void rearrange(CvMatF32Complex &img)
{
    CvMatF32Complex tmp(img.rows, img.cols);
    int cx = img.cols / 2;
    int cy = img.rows / 2;
    for (int r = 0; r < cy; r++) {
        for (int c = 0; c < cx; c++) {
            // top-left
            tmp(r, c) = img(cy+r, cx+c);
            // bottom-right
            tmp(cy+r, cx+c) = img(r, c);
            // top-right
            tmp(r, cx+c) = img(cy+r, c);
            // bottom-left
            tmp(cy, c) = img(r, cx+c);
        }
    }
    img = tmp;
}

// void normalizedLogTransform(cv::Mat &img)
// {
//     img = cv::abs(img);
//     img += cv::Scalar::all(1);
//     cv::log(img, img);
// }

} // end namespace FFTTools

#endif // FFTTOOLS_HPP_
